import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { List, Tools, Icon, Checkbox, Button, Tag, Modal } from 'weaver-mobile';
import { getFontColorFromBgHex } from '../../util';
import { renderLoading } from '../public';
const getLabel = Tools.getLabel;
const CheckboxItem = Checkbox.CheckboxItem;
const alert = Modal.alert;

@withRouter
@inject('communicationStore')
@observer
export default class Tags extends React.Component {
  static defaultProps = {
    prefixCls: 'cowork-communication-tag',
  }

  componentWillMount() {
    const { communicationStore: { tagStore }, location: { state } } = this.props;
    let { getCoworkLabelList, setStoreState, labelType, check } = tagStore;
    getCoworkLabelList();
    if (state && state.id) {
      if (state.labelList) {
        let labelArr = {...labelType};
        state.labelList && state.labelList.map(item => {
          labelArr[item.id] = true;
          return setStoreState({ check: ++check });
        });
        setStoreState({ labelType: labelArr });
      }
      setStoreState({ coworkids: state.id, page: state.page || 'view' });
    }
  }

  componentWillUnmount() {
    const { communicationStore: { tagStore } } = this.props;
    tagStore.clear();
  }

  // 标签
  markId = (id) => {
    const { communicationStore: { tagStore } } = this.props;
    let { check, setStoreState, labelType } = tagStore;
    let labelArr = {...labelType};
    if (!labelArr[id]) {
      labelArr[id] = true;
      setStoreState({ check: ++check });
    } else {
      labelArr[id] = false;
      setStoreState({ check: --check });
    }
    setStoreState({ labelType: labelArr });
  }

  // 取消所有的标签
  cancelLabel = () => {
    const { communicationStore: { tagStore } } = this.props;
    const { labelType, setStoreState, page, cancelMark } = tagStore;
    alert(page === 'view' ? getLabel('506097','确定要取消该协作的所有标签吗？') : getLabel('506098','确定要取消所选协作的所有标签吗？') ,'',[
      { text: getLabel(31129, '取消') },
      {
        text: getLabel(33703, '确认'),
        onPress: () => {
          Object.keys(labelType).forEach(item => {
            labelType[item] = false;
          })
          setStoreState({ check: 0 });
          cancelMark(this.submitTag);
        }
      },
    ])
  }

  // 标记为操作
  markType = (key) => {
    const { communicationStore: { tagStore } } = this.props;
    const { type, setStoreState } = tagStore;
    let typeArr = {};
    if (!type[key]) {
      typeArr[key] = true;
    } else {
      typeArr = {};
    }
    setStoreState({type: typeArr});
  }

  isDisabled = () => {
    const { communicationStore: { tagStore } } = this.props;
    const { labelType, type } = tagStore;
    let lableType = [];
    Object.keys(toJS(labelType)).forEach(item => {
      if (toJS(labelType)[item] !== false) {
        lableType.push(item);
      }
    })
    if (lableType.length === 0 && (JSON.stringify(toJS(type)) === '{}' || toJS(type) === "")){
      return true;
    } else {
      return false;
    }
  }

  submitTag = () => {
    const { communicationStore: { onHideCheck, tagStore, detailStore, coworkListStore, getCoworkList }, history, location } = this.props;
    if (tagStore.page === 'view' && location.pathname.includes('detail/tag')) {
      detailStore.viewCowork('', true);
      coworkListStore.clearData();
      getCoworkList();
    } else if (tagStore.page === 'list') {
      onHideCheck();
    }
    history.go(-1); 
  }

  render(){
    const { prefixCls, communicationStore: { tagStore }, location: { pathname } } = this.props;
    const { labelList, check, labelType, tagMark, tagLoading, markArr, page } = tagStore;
    let choose_rule = toJS(labelList).length > 0 && JSON.stringify(labelType) !== '{}' && check !== 0;
    return tagLoading ? renderLoading : (
      <div className={prefixCls}>
        <List>
          {
            markArr.map(item => {
              return (
                <List.Item 
                  key={item.key} 
                  extra={tagStore.type[item.key] ? <span><Icon type='check-circle'/></span> : ''} 
                  onClick={() => this.markType(item.key)}
                >{item.name}</List.Item>
              )
            })
          }
        </List>
        <div className={`${prefixCls}-chooseMark-box`}>
          <div className={`${prefixCls}-chooseMark`}>
            <List>
              <List.Item extra={<span onClick={() => this.props.history.push(labelList.length === 0 ? `${pathname}/createTag` : `${pathname}/manage`)}><Icon type='setting-up' /></span>}>{getLabel(390707, '选择标签')}</List.Item>
              <div className={`${prefixCls}-chooseMark-content`}>
                {
                  labelList.map((item, index) => {
                    return (
                      <CheckboxItem key={index} onClick={() => this.markId(item.id)} checked={labelType[item.id] || false}>
                        <Tag
                          style={{color: item.labelColor === '' ? '#333' : getFontColorFromBgHex(item.labelColor),backgroundColor: item.labelColor}}
                        >{item.labelName}</Tag>
                      </CheckboxItem>
                    )
                  })
                }
                {
                  (choose_rule || page === 'list') && <List.Item className={`${prefixCls}-chooseMark-content-cancelChoose`} onClick={this.cancelLabel}>{getLabel(31219, '取消所有标签')}</List.Item>
                }
              </div>
            </List>
          </div>
          <Button type='primary' disabled={this.isDisabled()} onClick={() => tagMark(() => this.submitTag())}>{getLabel(826, '确定')}</Button>
        </div>
      </div>
    );
  }
}

/* 
  说明：
  改页面使用需要通过location.state传递必要数据
*/